import { AppRouteRecordRaw } from '@/router/routes/types';
import { DEFAULT_LAYOUT } from '@/router/routes/base';

// 参数解析工具函数
const parseRouteParams = (paramsStr: string): Record<string, string> => {
  const params: Record<string, string> = {};

  if (!paramsStr) return params;

  // 处理特殊字符编码
  const decoded = decodeURIComponent(paramsStr.replace(/\+/g, ' '));

  // 解析参数对
  decoded.split('&').forEach((pair) => {
    const [key, value] = pair.split('=');
    if (key) {
      // 处理重复参数（保留最后一个值）
      params[key] = value || '';
    }
  });

  return params;
};

const generateRoutes = (
  menuData: any[],
  parentPath = '',
  isTopLevel = true
): AppRouteRecordRaw[] => {
  // menu_show
  return menuData.map((menu: any) => {
    const {
      menu_id,
      menu_name,
      menu_icon,
      menu_route_path,
      menu_component_path,
      menu_meta = {},
      menu_route_params,
      children = [],
      menu_show,
    } = menu;

    // 构建完整路径
    const fullPath = parentPath
      ? `${parentPath}/${menu_route_path}`
      : menu_route_path;

    // 构建路由元信息（合并原始meta和参数）
    const meta = {
      ...parseRouteParams(menu_route_params),
      locale: menu_name,
      requiresAuth: true,
      icon: menu_icon,
    };

    // 处理组件加载逻辑
    let component: any = null;
    if (isTopLevel && !menu_component_path) {
      component = DEFAULT_LAYOUT; // 仅顶级目录使用默认布局
    } else if (menu_component_path) {
      component = import.meta.glob('../views/**/*.vue')[
        `../views${menu_component_path}/index.vue`
      ];
    }

    // 递归生成子路由（子级不继承默认布局）
    const childrenRoutes =
      children.length > 0 ? generateRoutes(children, fullPath, false) : [];

    return {
      path: menu_route_path,
      name: getLastPathSegment(fullPath),
      component,
      menu_show,
      meta,
      children: childrenRoutes,
    };
  });
};

// 路径处理辅助函数
function getLastPathSegment(path: string): string {
  if (!path || path === '/') return 'home';

  const trimmed = path.replace(/\/+$/, '');
  const segments = trimmed.split('/');

  // 处理带参数的路径段（如 /user/:id）
  const lastSegment =
    segments[segments.length - 1] || segments[segments.length - 2];
  return lastSegment.replace(/:\w+$/, '');
}

export default generateRoutes;
